<template>
  <div class="culture-detail-page">
    <div class="page-container" v-loading="loading">
      <!-- 返回按钮 -->
      <div class="back-button">
        <el-button @click="$router.back()" :icon="ArrowLeft">
          返回列表
        </el-button>
      </div>

      <!-- 文化详情 -->
      <div class="culture-detail" v-if="cultureDetail">
        <!-- 头部信息 -->
        <div class="detail-header">
          <div class="header-image">
            <img :src="cultureDetail.coverImage || '/default-culture.jpg'" :alt="cultureDetail.title" />
            <div class="image-overlay">
              <div class="category-badge">
                {{ getCategoryText(cultureDetail.category) }}
              </div>
              <div class="recommend-badge" v-if="cultureDetail.isRecommend">
                <el-icon><Star /></el-icon>
                推荐
              </div>
            </div>
          </div>
          
          <div class="header-content">
            <h1>{{ cultureDetail.title }}</h1>
            <p class="subtitle" v-if="cultureDetail.subtitle">{{ cultureDetail.subtitle }}</p>
            <p class="summary">{{ cultureDetail.summary }}</p>
            
            <!-- 统计信息 -->
            <div class="stats-row">
              <div class="stat-item">
                <el-icon><View /></el-icon>
                <span>{{ cultureDetail.viewCount }} 浏览</span>
              </div>
              <div class="stat-item">
                <el-icon><StarFilled /></el-icon>
                <span>{{ cultureDetail.likeCount }} 点赞</span>
              </div>
              <div class="stat-item">
                <el-icon><Folder /></el-icon>
                <span>{{ cultureDetail.favoriteCount }} 收藏</span>
              </div>
              <div class="stat-item">
                <el-icon><Share /></el-icon>
                <span>{{ cultureDetail.shareCount }} 分享</span>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button 
                type="primary" 
                :icon="StarFilled" 
                @click="handleLike"
                :loading="likeLoading"
                :class="{ 'is-liked': isLiked }"
              >
                {{ isLiked ? '已点赞' : '点赞' }}
              </el-button>
              <el-button 
                :type="isFavorited ? 'warning' : 'default'"
                :icon="isFavorited ? StarFilled : Collection" 
                @click="handleFavorite"
                :loading="favoriteLoading"
                :class="{ 'is-favorited': isFavorited, 'favorite-button': true }"
                :disabled="favoriteLoading"
              >
                <template v-if="favoriteLoading">
                  {{ isFavorited ? '取消中...' : '收藏中...' }}
                </template>
                <template v-else>
                  {{ isFavorited ? '取消收藏' : '收藏' }}
                </template>
              </el-button>
              <el-button 
                :icon="Share" 
                @click="handleShare"
              >
                分享
              </el-button>
            </div>

            <!-- 元信息 -->
            <div class="meta-info">
              <div class="meta-item" v-if="cultureDetail.creatorName">
                <span class="label">作者:</span>
                <span class="value">{{ cultureDetail.creatorName }}</span>
              </div>
              <div class="meta-item">
                <span class="label">发布时间:</span>
                <span class="value">{{ formatDate(cultureDetail.createTime) }}</span>
              </div>
              <div class="meta-item">
                <span class="label">最后更新:</span>
                <span class="value">{{ formatDate(cultureDetail.updateTime) }}</span>
              </div>
              <div class="meta-item" v-if="cultureDetail.tags">
                <span class="label">标签:</span>
                <div class="tags">
                  <el-tag 
                    v-for="tag in getTags(cultureDetail.tags)" 
                    :key="tag" 
                    size="small"
                    class="clickable-tag"
                    @click.stop="searchByTag(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 详细内容 -->
        <div class="detail-content">
          <div class="content-section">
            <h2>详细内容</h2>
            <div class="content-text" v-html="cultureDetail.content"></div>
          </div>
        </div>

        <!-- 相关推荐 -->
        <div class="related-section" v-if="relatedList.length > 0">
          <div class="section-header">
            <h2><el-icon><Connection /></el-icon> 相关推荐</h2>
          </div>
          <div class="related-grid">
            <div
              v-for="item in relatedList"
              :key="item.id"
              class="related-item"
              @click="goToDetail(item.id)"
            >
              <div class="item-image">
                <img :src="item.coverImage || '/default-culture.jpg'" :alt="item.title" />
              </div>
              <div class="item-content">
                <h4>{{ item.title }}</h4>
                <p>{{ item.summary }}</p>
                <div class="item-stats">
                  <span><el-icon><View /></el-icon> {{ item.viewCount }}</span>
                  <span><el-icon><StarFilled /></el-icon> {{ item.likeCount }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 加载失败 -->
      <div class="error-state" v-if="error">
        <el-result
          :icon="errorInfo.icon"
          :title="errorInfo.title"
          :sub-title="errorInfo.subtitle"
        >
          <template #extra>
            <el-button type="primary" @click="fetchDetail" v-if="errorInfo.showRetry">重新加载</el-button>
            <el-button @click="$router.back()">返回列表</el-button>
          </template>
        </el-result>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  ArrowLeft, View, StarFilled, Folder, Share, Star, Connection, Collection
} from '@element-plus/icons-vue'
import { cultureApi } from '@/api'
import { useUserStore } from '@/stores/user'
import type { Culture } from '@/types/common'
import { CULTURE_CATEGORIES } from '@/types/common'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const error = ref(false)
const cultureDetail = ref<Culture | null>(null)
const relatedList = ref<Culture[]>([])
const interactionStatus = ref<any>({})

// 错误信息
const errorInfo = ref({
  icon: 'error',
  title: '加载失败',
  subtitle: '无法获取文化详情，请稍后重试',
  showRetry: true
})

// 交互状态
const likeLoading = ref(false)
const favoriteLoading = ref(false)
const isLiked = computed(() => interactionStatus.value.liked || false)
const isFavorited = computed(() => interactionStatus.value.favorited || false)

// 获取详情ID
const detailId = computed(() => Number(route.params.id))

// 获取交互状态
const fetchInteractionStatus = async () => {
  if (!userStore.isLoggedIn || !detailId.value) {
    // 未登录用户重置交互状态
    interactionStatus.value = {
      liked: false,
      favorited: false
    }
    return
  }
  
  try {
    console.log('获取用户交互状态，文化ID:', detailId.value)
    const response = await cultureApi.getInteractionStatus(detailId.value)
    const statusData = (response as any).data
    
    // 确保状态数据的完整性
    interactionStatus.value = {
      liked: statusData.liked || statusData.isLiked || false,
      favorited: statusData.favorited || statusData.isFavorited || false
    }
    
    console.log('交互状态更新完成:', interactionStatus.value)
  } catch (error) {
    console.error('获取交互状态失败:', error)
    // 失败时设置默认状态
    interactionStatus.value = {
      liked: false,
      favorited: false
    }
  }
}

// 获取文化详情
const fetchDetail = async () => {
  if (!detailId.value) {
    console.log('详情ID不存在:', detailId.value)
    return
  }

  console.log('开始获取详情，ID:', detailId.value, '登录状态:', userStore.isLoggedIn)
  loading.value = true
  error.value = false

  try {
    // 并发请求详情、相关内容和交互状态
    const promises = [
      cultureApi.getCultureDetail(detailId.value),
      cultureApi.getRelatedCultures(detailId.value, 0, 6) // category 0 表示获取所有分类
    ]

    // 如果用户已登录，获取交互状态
    if (userStore.isLoggedIn) {
      promises.push(cultureApi.getInteractionStatus(detailId.value) as Promise<any>)
    }

    const results = await Promise.allSettled(promises)
    console.log('API调用结果:', results.map(r => r.status))

    // 处理详情数据
    if (results[0].status === 'fulfilled') {
      cultureDetail.value = results[0].value.data as Culture
      console.log('详情数据加载成功:', cultureDetail.value)
      // 记录浏览
      cultureApi.recordView(detailId.value).catch(() => {})
    } else {
      console.error('详情API失败:', results[0].reason)
      throw new Error('获取详情失败')
    }

    // 处理相关内容
    if (results[1].status === 'fulfilled') {
      relatedList.value = results[1].value.data as Culture[]
    }

    // 处理交互状态（只有登录用户才有）
    if (userStore.isLoggedIn && results.length > 2 && results[2] && results[2].status === 'fulfilled') {
      interactionStatus.value = (results[2].value as any).data
    }

  } catch (err: any) {
    console.error('获取文化详情失败:', err)
    error.value = true
    
    // 根据错误类型显示不同的提示信息和页面状态
    if (err?.response?.status === 404) {
      errorInfo.value = {
        icon: 'warning',
        title: '内容不存在',
        subtitle: '抱歉，您要查看的文化内容不存在或已被删除',
        showRetry: false
      }
      ElMessage.error('文化内容不存在或已被删除')
    } else if (err?.response?.status === 500) {
      errorInfo.value = {
        icon: 'error',
        title: '服务器错误',
        subtitle: '服务器出现内部错误，请稍后重试',
        showRetry: true
      }
      ElMessage.error('服务器内部错误，请稍后重试')
    } else if (err?.response?.status === 403) {
      errorInfo.value = {
        icon: 'warning',
        title: '访问受限',
        subtitle: '您暂无权限访问此内容',
        showRetry: false
      }
      ElMessage.error('暂无访问权限')
    } else if (err?.message?.includes('timeout') || err?.code === 'ECONNABORTED') {
      errorInfo.value = {
        icon: 'warning',
        title: '请求超时',
        subtitle: '网络连接超时，请检查网络连接后重试',
        showRetry: true
      }
      ElMessage.error('请求超时，请检查网络连接')
    } else if (err?.message?.includes('Network Error')) {
      errorInfo.value = {
        icon: 'warning',
        title: '网络异常',
        subtitle: '网络连接异常，请检查网络后重试',
        showRetry: true
      }
      ElMessage.error('网络连接异常，请检查网络')
    } else {
      errorInfo.value = {
        icon: 'error',
        title: '加载失败',
        subtitle: '获取文化详情失败，请稍后重试',
        showRetry: true
      }
      ElMessage.error('获取文化详情失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 防抖定时器
let likeDebounceTimer: number | null = null

// 点赞操作
const handleLike = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (!cultureDetail.value) {
    return
  }

  // 防止重复点击和防抖处理
  if (likeLoading.value) {
    return
  }

  // 清除之前的防抖定时器
  if (likeDebounceTimer) {
    clearTimeout(likeDebounceTimer)
  }

  // 设置防抖，300ms内只能点击一次
  likeDebounceTimer = setTimeout(async () => {
    await performLikeOperation()
  }, 300)
}

// 执行点赞操作
const performLikeOperation = async () => {
  if (!cultureDetail.value) return

  // 检查用户登录状态
  const userStore = useUserStore()
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再点赞')
    router.push('/login')
    return
  }

  likeLoading.value = true
  
  // 保存当前状态用于回滚
  const originalLiked = interactionStatus.value.liked || false
  const originalLikeCount = cultureDetail.value.likeCount
  
  // 乐观更新：立即更新UI
  const newLikedStatus = !originalLiked
  interactionStatus.value.liked = newLikedStatus
  cultureDetail.value.likeCount = newLikedStatus 
    ? originalLikeCount + 1 
    : Math.max(0, originalLikeCount - 1)
  
  try {
    console.log('发送点赞请求，当前状态:', {
      originalLiked,
      originalLikeCount,
      newLikedStatus
    })
    
    const response = await cultureApi.likeCulture(detailId.value)
    console.log('点赞API响应:', response)
    
    // 确认后端返回的状态
    const responseData = (response as any).data
    console.log('解析响应数据:', responseData)
    
    const serverLikedStatus = responseData.isLiked || responseData.liked
    const serverLikeCount = responseData.likeCount
    
    console.log('服务器状态:', {
      serverLikedStatus,
      serverLikeCount,
      isLiked: responseData.isLiked,
      liked: responseData.liked
    })
    
    // 使用服务器返回的准确数据
    interactionStatus.value.liked = serverLikedStatus
    if (typeof serverLikeCount === 'number') {
      cultureDetail.value.likeCount = serverLikeCount
    }
    
    console.log('更新后的前端状态:', {
      liked: interactionStatus.value.liked,
      likeCount: cultureDetail.value.likeCount
    })
    
    ElMessage.success(serverLikedStatus ? '点赞成功' : '取消点赞')
  } catch (error: any) {
    console.error('点赞操作失败:', error)
    
    // 回滚乐观更新
    interactionStatus.value.liked = originalLiked
    cultureDetail.value.likeCount = originalLikeCount
    
    let errorMessage = '操作失败，请稍后重试'
    
    if (error.response?.status === 400) {
      errorMessage = '请求参数错误，请检查登录状态'
    } else if (error.response?.status === 401) {
      errorMessage = '登录已过期，请重新登录'
      userStore.logout()
      router.push('/login')
    } else if (error.message) {
      // 解析后端返回的具体错误信息
      if (error.message.includes('Duplicate entry')) {
        errorMessage = '点赞状态异常，已为您刷新状态'
        // 重新获取交互状态
        fetchInteractionStatus()
      } else if (error.message.includes('并发冲突')) {
        errorMessage = '操作过于频繁，请稍后重试'
      } else if (error.message.includes('重试次数超限')) {
        errorMessage = '网络繁忙，请稍后重试'
      } else {
        // 使用后端返回的错误信息
        const backendMessage = error.message.replace('点赞操作失败: ', '')
        if (backendMessage && backendMessage !== error.message) {
          errorMessage = backendMessage
        }
      }
    }
    
    ElMessage.error(errorMessage)
  } finally {
    likeLoading.value = false
  }
}

// 防抖定时器
let favoriteDebounceTimer: number | null = null

// 收藏操作
const handleFavorite = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (!cultureDetail.value) return

  // 防止重复点击
  if (favoriteLoading.value) {
    return
  }

  // 清除之前的防抖定时器
  if (favoriteDebounceTimer) {
    clearTimeout(favoriteDebounceTimer)
  }

  // 设置防抖，300ms内只能点击一次
  favoriteDebounceTimer = setTimeout(async () => {
    await performFavoriteOperation()
  }, 300)
}

// 执行收藏操作
const performFavoriteOperation = async () => {
  if (!cultureDetail.value) return

  // 检查用户登录状态
  const userStore = useUserStore()
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再收藏')
    router.push('/login')
    return
  }

  favoriteLoading.value = true
  
  // 保存当前状态用于回滚
  const originalFavorited = interactionStatus.value.favorited || false
  const originalFavoriteCount = cultureDetail.value.favoriteCount
  
  // 预期的新状态
  const expectedNewStatus = !originalFavorited
  
  // 乐观更新：立即更新UI以提供即时反馈
  interactionStatus.value.favorited = expectedNewStatus
  cultureDetail.value.favoriteCount = expectedNewStatus 
    ? originalFavoriteCount + 1 
    : Math.max(0, originalFavoriteCount - 1)

  try {
    console.log('执行收藏操作:', {
      action: expectedNewStatus ? '收藏' : '取消收藏',
      originalFavorited,
      expectedNewStatus,
      cultureId: detailId.value
    })

    const response = await cultureApi.favoriteCulture(detailId.value)
    const responseData = (response as any).data
    
    // 从服务器响应中获取准确状态
    const serverFavoritedStatus = responseData.isFavorited || responseData.favorited
    const serverFavoriteCount = responseData.favoriteCount
    
    console.log('服务器返回状态:', {
      serverFavoritedStatus,
      serverFavoriteCount,
      expectedNewStatus
    })
    
    // 使用服务器返回的准确数据更新状态
    interactionStatus.value.favorited = serverFavoritedStatus
    if (typeof serverFavoriteCount === 'number') {
      cultureDetail.value.favoriteCount = serverFavoriteCount
    }
    
    // 显示操作结果消息
    const actionText = serverFavoritedStatus ? '收藏成功！' : '已取消收藏'
    ElMessage.success({
      message: actionText,
      duration: 2000,
      showClose: true
    })
    
    // 验证状态一致性
    if (serverFavoritedStatus !== expectedNewStatus) {
      console.warn('状态不一致，服务器状态与预期不符:', {
        expected: expectedNewStatus,
        actual: serverFavoritedStatus
      })
    }
    
    console.log('收藏状态更新完成:', {
      favorited: interactionStatus.value.favorited,
      favoriteCount: cultureDetail.value.favoriteCount
    })
    
  } catch (error: any) {
    console.error('收藏操作失败:', error)
    
    // 回滚乐观更新到原始状态
    interactionStatus.value.favorited = originalFavorited
    cultureDetail.value.favoriteCount = originalFavoriteCount
    
    // 错误处理和用户提示
    let errorMessage = '操作失败，请稍后重试'
    
    if (error.response?.status === 400) {
      errorMessage = '请求参数错误，请检查登录状态'
    } else if (error.response?.status === 401) {
      errorMessage = '登录已过期，请重新登录'
      userStore.logout()
      router.push('/login')
      return
    } else if (error.message) {
      if (error.message.includes('Duplicate entry')) {
        errorMessage = '收藏状态异常，正在刷新...'
        // 重新获取准确的交互状态
        setTimeout(() => {
          fetchInteractionStatus()
        }, 1000)
      } else if (error.message.includes('并发冲突')) {
        errorMessage = '操作过于频繁，请稍后重试'
      } else if (error.message.includes('重试次数超限')) {
        errorMessage = '网络繁忙，请稍后重试'
      } else {
        const backendMessage = error.message.replace('收藏操作失败: ', '')
        if (backendMessage && backendMessage !== error.message) {
          errorMessage = backendMessage
        }
      }
    }
    
    ElMessage.error({
      message: errorMessage,
      duration: 3000,
      showClose: true
    })
  } finally {
    favoriteLoading.value = false
  }
}

// 分享操作
const handleShare = async () => {
  try {
    if (navigator.share) {
      await navigator.share({
        title: cultureDetail.value?.title,
        text: cultureDetail.value?.summary,
        url: window.location.href
      })
    } else {
      // 复制链接到剪贴板
      await navigator.clipboard.writeText(window.location.href)
      ElMessage.success('链接已复制到剪贴板')
    }

    // 增加分享数
    if (cultureDetail.value) {
      cultureApi.shareCulture(detailId.value).catch(() => {})
      cultureDetail.value.shareCount++
    }
  } catch (error) {
    // 用户取消分享或其他错误
    if (error instanceof Error && error.name !== 'AbortError') {
      ElMessage.error('分享失败')
    }
  }
}

// 跳转到详情页
const goToDetail = (id: number) => {
  router.push(`/culture/${id}`)
}

// 按标签搜索
const searchByTag = (tag: string) => {
  console.log('点击标签:', tag) // 添加调试日志
  if (!tag || !tag.trim()) {
    console.error('标签为空')
    return
  }
  
  try {
    router.push({
      path: '/search',
      query: { keyword: tag.trim(), tab: 'culture' }
    })
    console.log('路由跳转成功')
  } catch (error) {
    console.error('路由跳转失败:', error)
    ElMessage.error('跳转失败')
  }
}

// 获取分类文本
const getCategoryText = (category: number) => {
  return CULTURE_CATEGORIES[category as keyof typeof CULTURE_CATEGORIES] || '其他'
}

// 获取标签数组
const getTags = (tagsString: string) => {
  if (!tagsString) {
    console.log('标签字符串为空')
    return []
  }
  
  const tags = tagsString.split(',').filter(tag => tag.trim()).map(tag => tag.trim())
  console.log('解析的标签:', tags)
  return tags
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

onMounted(() => {
  fetchDetail()
})

// 监听路由变化，重新获取详情
watch(() => route.params.id, (newId) => {
  if (newId && newId !== String(detailId.value)) {
    fetchDetail()
  }
})

// 监听用户登录状态变化
watch(() => userStore.isLoggedIn, (isLoggedIn) => {
  if (isLoggedIn) {
    // 用户登录后重新获取交互状态
    fetchInteractionStatus()
  } else {
    // 用户退出登录时重置交互状态
    interactionStatus.value = {
      liked: false,
      favorited: false
    }
  }
}, { immediate: false })
</script>

<style scoped>
.culture-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.culture-detail {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 头部信息 */
.detail-header {
  position: relative;
}

.header-image {
  position: relative;
  height: 300px;
  overflow: hidden;
}

.header-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-overlay {
  position: absolute;
  top: 20px;
  left: 20px;
  display: flex;
  gap: 12px;
}

.category-badge {
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
}

.recommend-badge {
  background: linear-gradient(135deg, #d32f2f, #f57c00);
  color: #fff;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 4px;
}

.header-content {
  padding: 32px;
}

.header-content h1 {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
  line-height: 1.3;
}

.subtitle {
  font-size: 18px;
  color: #666;
  margin-bottom: 16px;
  font-weight: 500;
}

.summary {
  font-size: 16px;
  color: #666;
  line-height: 1.6;
  margin-bottom: 24px;
}

.stats-row {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #666;
}

.stat-item .el-icon {
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-bottom: 32px;
}

.action-buttons .el-button.is-liked {
  background: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
}

.action-buttons .el-button.is-favorited {
  background: #e6a23c;
  border-color: #e6a23c;
  color: #fff;
  transform: scale(1.02);
  box-shadow: 0 2px 8px rgba(230, 162, 60, 0.3);
}

.favorite-button {
  transition: all 0.3s ease;
  position: relative;
}

.favorite-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.favorite-button.is-favorited:hover {
  background: #d4af37;
  border-color: #d4af37;
  box-shadow: 0 4px 12px rgba(212, 175, 55, 0.4);
}

.favorite-button:active {
  transform: translateY(0);
}

.favorite-button.is-favorited {
  animation: favoriteSuccess 0.6s ease-out;
}

@keyframes favoriteSuccess {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1.02);
  }
}

.meta-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.meta-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.meta-item .label {
  color: #999;
  margin-right: 8px;
  min-width: 80px;
}

.meta-item .value {
  color: #333;
}

.tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tags .el-tag.clickable-tag {
  cursor: pointer;
  transition: all 0.3s;
  user-select: none;
}

.tags .el-tag.clickable-tag:hover {
  background: #d32f2f;
  color: #fff;
  border-color: #d32f2f;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(211, 47, 47, 0.3);
}

.tags .el-tag.clickable-tag:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(211, 47, 47, 0.5);
}

/* 详细内容 */
.detail-content {
  padding: 32px;
  border-top: 1px solid #f0f0f0;
}

.content-section h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #d32f2f;
  display: inline-block;
}

.content-text {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
}

.content-text :deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 16px 0;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.content-text :deep(p) {
  margin-bottom: 16px;
}

.content-text :deep(h1),
.content-text :deep(h2),
.content-text :deep(h3),
.content-text :deep(h4),
.content-text :deep(h5),
.content-text :deep(h6) {
  margin: 24px 0 16px;
  color: #333;
  font-weight: bold;
}

.content-text :deep(ul),
.content-text :deep(ol) {
  padding-left: 24px;
  margin-bottom: 16px;
}

.content-text :deep(li) {
  margin-bottom: 8px;
}

/* 相关推荐 */
.related-section {
  padding: 32px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.section-header h2 {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.related-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.related-item {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.related-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.item-image {
  height: 120px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.related-item:hover .item-image img {
  transform: scale(1.05);
}

.item-content {
  padding: 16px;
}

.item-content h4 {
  font-size: 14px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-content p {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-stats {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.item-stats span {
  display: flex;
  align-items: center;
  gap: 2px;
}

.error-state {
  padding: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .header-content {
    padding: 24px 20px;
  }

  .header-content h1 {
    font-size: 24px;
  }

  .stats-row {
    flex-wrap: wrap;
    gap: 16px;
  }

  .action-buttons {
    flex-wrap: wrap;
  }

  .meta-info {
    grid-template-columns: 1fr;
  }

  .detail-content {
    padding: 24px 20px;
  }

  .related-section {
    padding: 24px 20px;
  }

  .related-grid {
    grid-template-columns: 1fr;
  }
}
</style>
